'use strict';

const { Service } = require('egg');
const uuidv1 = require('uuid/v1');

class SchoolService extends Service {
  async getList(offset, limit, option) {
    const { ctx, app } = this;
    const db = app.mysql.get('spring');
    const pageCondition = {
      where: {},
      offset,
    };
    if (limit) {
      pageCondition.limit = limit;
    }
    if (option && option.educationType) {
      pageCondition.where.education_type = option.educationType;
    }
    const condition = Object.assign({}, pageCondition);
    let result = await db.select('t_school', condition);
    result = ctx.camelcaseKeys(result);
    return result;
  }

  async getCount(option) {
    const { app } = this;
    const db = app.mysql.get('spring');
    let sql = 'select count(*) as count from t_school';
    if (option && option.educationType) {
      sql += ` where education_type = '${option.educationType}'`;
    }
    const result = await db.query(sql);
    return result.length ? result[0].count : 0;
  }

  async create(school) {
    const { app } = this;
    const db = app.mysql.get('spring');
    const { province, city, area, schoolName, address, educationType } = school;
    const schoolId = uuidv1();
    try {
      const result = await db.insert('t_school', {
        province,
        city,
        area,
        school_id: schoolId,
        school_name: schoolName,
        address,
        education_type: educationType,
      });
      return result;
    } catch (e) {
      return e;
    }
  }
}

module.exports = SchoolService;
